#!/bin/bash

export SCRIPT_DIR=$(dirname "$0")

##
## Configuration Variables
##

config ()
{
    # A whitespace-separated list of executables that must be present and locatable.
    : ${REQUIRED_TOOLS="xctool cmake"}

    export REQUIRED_TOOLS
}

##
## Bootstrap Process
##

main ()
{
    config

    if [ -n "$REQUIRED_TOOLS" ]
    then
        echo "*** Checking dependencies..."
        check_deps
    fi

    local submodules=$(git submodule status)
    local result=$?

    if [ "$result" -ne "0" ]
    then
        exit $result
    fi

    if [ -n "$submodules" ]
    then
        echo "*** Updating submodules..."
        update_submodules
    fi
}

check_deps ()
{
    for tool in $REQUIRED_TOOLS
    do
        which -s "$tool"
        if [ "$?" -ne "0" ]
        then
            echo "*** Error: $tool not found. Please install it and bootstrap again."
            exit 1
        fi
    done

    # Ensure that we have libgit2's dependencies installed.
    installed=`brew list`
    libs="libssh2 libtool autoconf automake pkg-config"

    for lib in $libs
    do
        # Skip packages that are already installed.
        echo "$installed" | grep -q "$lib" && code=$? || code=$?

        if [ "$code" -eq "0" ]
        then
            continue
        elif [ "$code" -ne "1" ]
        then
            exit $code
        fi

        echo "*** Installing $lib with Homebrew..."
        brew install "$lib"
    done

    brew_prefix=`brew --prefix`
    expected_prefix=/usr/local

    if [ "$brew_prefix" != "$expected_prefix" ]
    then
        echo "*** Adding soft links into $expected_prefix..."

        products=(lib/libssh2.a include/libssh2.h include/libssh2_sftp.h include/libssh2_publickey.h)

        for product in "${products[@]}"
        do
            destination="$expected_prefix/$product"
            if [ -e "$destination" ]
            then
                continue
            fi

            sudo mkdir -p "$(dirname "$destination")"
            sudo ln -s "$brew_prefix/$product" "$destination"
        done
    fi
}

bootstrap_submodule ()
{
    local bootstrap="script/bootstrap"

    if [ -e "$bootstrap" ]
    then
        echo "*** Bootstrapping $name..."
        "$bootstrap" >/dev/null
    else
        update_submodules
    fi
}

update_submodules ()
{
    git submodule sync --quiet && git submodule update --init && git submodule foreach --quiet bootstrap_submodule
}

export -f bootstrap_submodule
export -f update_submodules

main
